<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(1,1)"
          v-hasPermi="['food:foodclassify:add']"
        >新增一级分类</el-button>
      </el-col>
    </el-row>
  
      <el-table
      v-loading="loading"
      :data="tableData"
      row-key="id"
      :default-expand-all="false"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >

      <el-table-column prop="label" label="分类名称" :show-overflow-tooltip="true" width="360"></el-table-column>
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <div class="top-img">
          <img :src="'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/'+scope.row.cover[0].url" v-if="scope.row.cover[0]" class="avatar"/> 
          </div>
        </template>
      </el-table-column>      
      <el-table-column prop="count" label="数量" :show-overflow-tooltip="true" width="160"></el-table-column>
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:menu:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row,2)"
            v-if="scope.row.children"
            v-hasPermi="['system:menu:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:menu:remove']"
          >删除</el-button>
        </template>
      </el-table-column>

      </el-table>


     <!-- 添加或修改《中国食物成分》分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
         <!-- <el-form-item label="ID" prop="id" v-if="form.id">
          <el-input v-model="form.id" placeholder="请输入ID号" disabled />
        </el-form-item>   -->

        <!-- <el-form-item label="父级" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入父级" />
        </el-form-item>   -->


        <el-form-item label="父级" prop="parentId" v-if="form.parentId != 0">
          <el-select v-model="form.parentId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>  
        </el-form-item>             
      
         
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
       <el-form-item label="分类图片" >
            <el-upload
              ref="upload"
              list-type="picture-card"
              :on-remove="handleRemove"
              :http-request="handleUploadFile"
              :file-list="fullCover"
              action="https://jsonplaceholder.typicode.com/posts/"
              >
              <i class="el-icon-plus"></i>
            </el-upload>          
        </el-form-item> 
       <!-- <el-form-item label="食物条数" prop="count">
          <el-input v-model="form.count" placeholder="请输入食物条数" disabled/>
        </el-form-item>         -->
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入食物类编码" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入食物类编码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listFoodclassify, getFoodclassify, delFoodclassify, addFoodclassify, updateFoodclassify } from "@/api/food/foodclassify";
import {
	put,
	getUrl,
} from '@/components/Upload/uploadOss.js'

export default {
  name: "Foodclassify",
  watch:{
    'form.cover'() {
      if(this.form.cover){
        this.fullCover = this.form.cover.map(item => (
                {
                  ...item,
                  url: 'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + item.url
                }
          )
        )
      }
    }
  },   
  data() {
    return {
      fullCover: [],
      options: [],
      tableData: [],
      treeData: [],
			defaultProps: {
				children: 'children',
				label: 'label'
			},    
      foodclassifyList: [],
      queryParams:{
				page: 1,
				pageSize: 200,
      },
      // 表单参数
      form: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,     

      // 表单校验
      rules: {
        versionId: [
          { required: true, message: "版次id不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "食物类编码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        cover: [
          { required: true, message: "请上传图片", trigger: "blur" }
        ],       
        count: [
          { required: true, message: "食物条数不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父级不能为空", trigger: "blur" }
        ],
      }  
   
    };
  },
  created() {
    this.getList();
    this.getParentList();
  },
  methods: {
		// 获取当前年月日
		getDate() {
			const date = new Date()
			var year = date.getFullYear()
			var month = date.getMonth() + 1
			var day = date.getDate()
			month = month > 9 ? month : '0' + month
			day = day < 10 ? '0' + day : day
			var today = year + month + day
			return today
		},
    handleRemove(file, fileList) {
      console.log(file);
      this.form.cover = this.form.cover.filter((item)=>('http://health-fcd.oss-cn-hangzhou.aliyuncs.com/'+item.url) != file.url)
      console.log(this.form.cover);
    },
    handleUploadFile(option) {
      this.loading = true
      //获取上传后的url
      const _name = this.getDate() + '/' + option.file.uid + '.' + option.file.name.split('.')[1]
      put(_name, option.file).then((res) => {
        if (res) {
          getUrl(res.name).then((rel) => {
            this.form.cover.push({
              url: _name
            })
            this.$refs.upload.clearFiles()
          })
        } else {
          this.$refs.upload.clearFiles()
        }
          this.loading = false
      })
		},

		handleNodeClick(data) {

		},   
    getParentList(){

      listFoodclassify({
        parentId: 0,
        ...this.queryParams
      }).then(response => {
        this.options = response.rows;
      });      
    }, 
    /** 查询《中国食物成分》分类列表 */
    getList() {
      this.loading = true;

      listFoodclassify(this.queryParams).then(response => {
        this.treeData = response.rows;
        this.datareload();
        this.loading = false;
      });
      

    },
    
		datareload() {
			this.tableData = [];
      let pcount = 0;
			for (var i = 0; i < this.treeData.length; i++) {
				if (this.treeData[i].parentId == 0) {
					let obj = {}
					let children = []
					obj.label = this.treeData[i].name
					obj.id = this.treeData[i].id
					obj.count = this.treeData[i].count
					obj.versionId = this.treeData[i].versionId
					obj.cover = this.treeData[i].cover
					for (var j = 0; j < this.treeData.length; j++) {
						let childer = []
						if (this.treeData[j].parentId !== 0 && this.treeData[j].parentId == this.treeData[i].id) {
							let list = {}
							list.label = this.treeData[j].name
							list.id = this.treeData[j].id
							list.count = this.treeData[j].count
							list.versionId = this.treeData[j].versionId
							list.cover = this.treeData[j].cover
							children.push(list)
						}
					}
					obj.children = children
					this.tableData.push(obj)
				}
			}
      console.log('static12345',this.tableData);
      this.tableData.forEach((item,index)=>{
          pcount = 0;
          pcount = item.children.reduce((accumulator, current) => {
            return Number(accumulator) + Number(current.count);
          }, 0)
          console.log('static222',pcount);
          this.tableData[index].count = pcount;
          // console.log('static4444',pcount);
      })
      this.$forceUpdate();
		},

    renderContent(h, { node, data, store }) {
			return (
				<div>
					<span>
						<span style="font-size:14px;">{node.label}</span>
					</span>
					<span style="float: right; margin-right: 20px">
						<el-tag size="small"  style="margin-right: 20px;margin-left: 20px" on-click={() => this.handleRowEdit(store, data)}>编辑</el-tag>
						<el-tag size="small" type="danger" on-click={() => this.handleRowDelete(store, data)}>删除</el-tag>
					</span>
				</div>);
		},

  handleRowEdit(store, data){
      this.reset();
      const id = data.id

      getFoodclassify(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改《中国食物成分》分类";
      }); 
  },

  handleRowDelete(store, data){
      const ids = data.id;
      this.$modal.confirm('是否确认删除《中国食物成分》分类编号为"' + ids + '"的数据项？').then(function() {
        return delFoodclassify(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});    
  },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        versionId: null,
        code: null,
        cover: [],
        name: null,
        enName: null,
        count: null,
        parentId: null,
        remark: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },

    /** 新增按钮操作 */
    handleAdd(row,index) {
        this.reset();
        this.open = true;
        this.title = "添加《中国食物成分》分类";      
      if(index == 2){
        this.form.parentId = row.id
      } else {
        this.form.parentId = 0
      }

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFoodclassify(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改《中国食物成分》分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFoodclassify(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFoodclassify(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            this.$router.go(0);
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('static',row);
      if(row.children && row.children.length!=0){
        this.$message({
          message: '请先删除子分类',
          type: 'warning'
        });
        return
      }
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除《中国食物成分》分类名称为"' + row.label + '"的数据项？').then(function() {
        return delFoodclassify(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.$router.go(0);
      }).catch(() => {});
    },

  }
};
</script>

<style lang="scss" scoped>


.el-tree{
  margin: 20px !important;
}

.el-tree-node__content{
  margin-top: 5px !important;
}
.top-img{
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
}

  .avatar {
    width: 58px;
    height: 58px;
    display: block;
  }
</style> 